package com.example.jetpacktest.livedata

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import java.util.*

class TimerWithLiveDataViewModel : ViewModel() {

    var count: MutableLiveData<Int>? = MutableLiveData()
    var timer: Timer? = null


    fun startCount() {
        if (timer == null) {
            timer = Timer()
        }
        count?.value = 0
        timer?.schedule(object : TimerTask() {
            override fun run() {
//                postValue()方法用在非UI线程中，若在UI线程中，则使用setValue()方法
                count?.postValue(count?.value!! + 1)
            }
        }, 1000, 1000)
    }

    override fun onCleared() {
        super.onCleared()
        timer?.cancel()
    }

}